<?php
require __DIR__ . "/vendor/autoload.php";
require_once 'const.php';

use core\classes\ColorEcho;
use core\classes\Request;

ColorEcho::red(" 欢迎使用EZNAT穿透\r\n", '');
$conf['channel_ip'] = "nwct.istiny.cc";
$conf['channel_port'] = "8888";
$conf['check_running_cycle'] = 1;
$conf['online_cycle'] = 3;
$authIp = "//auth.istiny.cc";

$stdinEmail = fopen("php://stdin", "r");
$stdinPassword = fopen("php://stdin", "r");
$email = waitInput(" 请输入账号：");

$password = waitInput(" 请输入密码：");
$request = new Request($email, $password, $authIp);
$data = $request->login();
if (!$data) {
    die(' 账号或者密码错误');
}

$clientList = $request->getClientList();
if (!empty($clientList)) {
    foreach ($clientList as $c) {
        echo "  id:{$c['id']}, 名称:{$c['name']}，data_bus:{$c['data_bus']}\r\n";
    }
} else {
    ColorEcho::red(" 没有可用的客户端，请到http://eznat.istiny.cc创建客户端后重试\r\n");
    exit;
}

$find = false;
do {
    $clientId = waitInput(" 输入客户端ID:");
    foreach ($clientList as $c) {
        if ($c['id'] == $clientId) {
            $find = true;
            $conf['data_bus'] = $c['data_bus'];
            break;
        }
    }
    if (!$find) {
        ColorEcho::red(" 客户端ID不正确\r\n");
    }
} while (!$find);
file_put_contents("./conf/conf.ini", arr2ini($conf));
ColorEcho::blue("配置成功\r\n");
function arr2ini(array $a, array $parent = array())
{
    $out = '';
    foreach ($a as $k => $v) {
        if (is_array($v)) {
            //subsection case
            //merge all the sections into one array...
            $sec = array_merge((array)$parent, (array)$k);
            //add section information to the output
            $out .= '[' . join('.', $sec) . ']' . PHP_EOL;
            //recursively traverse deeper
            $out .= arr2ini($v, $sec);
        } else {
            //plain key->value case
            $out .= "$k=$v" . PHP_EOL;
        }
    }
    return $out;
}

function waitInput($message, $default = "")
{
    $name = fopen("php://stdin", "r");
    while (true) {
        ColorEcho::yellow($message);
        $value = fgets($name);
        if (empty(trim($value))) {
            if (!empty($default)) {
                return $default;
            }
            continue;
        } else {
            fclose($name);
            return $value;
            break;
        }
    }
}
